<template lang="pug">
  el-row
    el-col(:span="24")
      .grid-content
        el-form.red-envelope-rule-form(:model="redEnvelopeRuleForm", :rules="redEnvelopeRules", ref="redEnvelopeRuleForm", label-width="180px")
          el-form-item.name(label="红包名称", prop="name")
            el-input(v-model="redEnvelopeRuleForm.name", placeholder="用以区分不同的红包活动，例：红包活动20181001", style="width:500px")
          el-form-item.range(label="红包范围")
            el-tooltip(effect="dark", placement="top")
              div(slot="content")
                | 1.指定产品：指定某个产品可领红包；
                br
                | 2.指定二维码：扫描指定的二维码后方可领红包；
                br
                | 3.某类产品：设置某类产品扫描后皆可领取红包；
                br
                | 4.企业所有产品：只要是本企业的产品，皆可领取红包
              i.el-icon-question
            el-radio(v-model="redEnvelopeRuleForm.range", label="0" border) 指定产品
            el-radio(v-model="redEnvelopeRuleForm.range", label="1" border) 指定二维码
            el-radio(v-model="redEnvelopeRuleForm.range", label="2" border) 某类产品
            el-radio(v-model="redEnvelopeRuleForm.range", label="3" border) 企业所有产品
          template(v-if="redEnvelopeRuleForm.range === '0'")
            el-form-item.code1(label="产品追溯码前11位", prop="code1")
              el-input(v-model="redEnvelopeRuleForm.code1", style="width:500px")
          template(v-if="redEnvelopeRuleForm.range === '1'")
            el-form-item.qrcode(label="参与二维码")
              el-select(v-model="redEnvelopeRuleForm.qrcode", placeholder="选择参与二维码")
                el-option(label="全部", value="1")
            el-form-item.type(label="红包中奖机制")
              el-radio(v-model="redEnvelopeRuleForm.mechanism", label=0 border) 100%中奖
              el-radio(v-model="redEnvelopeRuleForm.mechanism", label=1 border) 随机中奖
          template(v-if="redEnvelopeRuleForm.range === '2'")
            el-form-item.code2(label="产品登记证号", prop="code2")
              el-input(v-model="redEnvelopeRuleForm.code2", style="width:500px")
          template(v-if="redEnvelopeRuleForm.range === '3'")
            template(v-if="redEnvelopeRuleForm.isCertification")
              el-form-item.companyName(label="企业名称")
                el-input(v-model="redEnvelopeRuleForm.companyName", style="width:500px")
            template(v-else)
              el-form-item.companyName(label="企业名称")
                a.certification-false.go-to-certification(v-on:click="goToCertification") 企业尚未认证，去认证>
          el-form-item.type(label="红包类型")
            el-radio(v-model="redEnvelopeRuleForm.type", label="0" border) 随机金额
            el-radio(v-model="redEnvelopeRuleForm.type", label="1" border) 固定金额
          template(v-if="redEnvelopeRuleForm.type === '0'")
            el-form-item.amount(label="单个红包金额")
              a 0.1元 ~ 200元
          template(v-if="redEnvelopeRuleForm.type === '1'")
            el-form-item.amount(label="单个红包金额", prop="number1")
              el-input(v-model="redEnvelopeRuleForm.number1", placeholder="0.1元 ~ 200元", style="width:500px")
          el-form-item.total-number(label="红包总个数", prop="number2")
            el-input(v-model="redEnvelopeRuleForm.number2", placeholder="输入大于0的整数", style="width:500px")
              template(slot="append") 个
          el-form-item.total-amount(label="红包总金额", prop="number3")
            el-input(v-model="redEnvelopeRuleForm.number3", placeholder="输入大于0的整数", style="width:500px")
              template(slot="append") 元
            span.tips
              a 手续费：25.00 元
              a （按红包总金额的<span style="color:#e52a33">5%</span>收取）
          el-form-item.region(label="红包发放区域")
            el-radio(v-model="redEnvelopeRuleForm.region", label="0" border) 无指定区域
            el-radio(v-model="redEnvelopeRuleForm.region", label="1" border) 指定区域
            el-radio(v-model="redEnvelopeRuleForm.region", label="2" border) 指定农资店
          template(v-if="redEnvelopeRuleForm.region === '1'")
            el-table(ref="multipleTable", :data="provinceList", tooltip-effect="dark", height="300")
              el-table-column(label="省", width="176")
                template(slot-scope="scope")
                  el-checkbox-group(v-model="redEnvelopeRuleForm.selectProvinceList")
                    el-checkbox(:label="scope.row.provinceCode", v-on:change="handleCheckedProvincesChange(scope.row)") {{scope.row.province}}
              el-table-column(label="市")
                template(slot-scope="scope")
                  el-checkbox-group(v-model="redEnvelopeRuleForm.selectCityList")
                    span.city-list(v-for="( item, index ) in scope.row.cityList")
                      el-checkbox(:label="item.cityCode", :key="index", v-on:change="handleCheckedCitiesChange(item)") {{item.city}}
                      i.el-icon-edit(v-on:click="handleCheckedCitiesChangeClick(item, scope.row.cityList)")
            template(v-if="isShowCounty")
              el-table(ref="multipleTable", :data="countyList", tooltip-effect="dark", height="300")
                el-table-column(:label="redEnvelopeRuleForm.selectCity", width="176")
                  template(slot-scope="scope")
                    el-checkbox-group(v-model="redEnvelopeRuleForm.selectCountyList")
                      el-checkbox(:label="scope.row.countyCode", v-on:change="handleCheckedCountiesChange(scope.row)") {{scope.row.county}}
                el-table-column(label="乡镇/街道")
                  template(slot-scope="scope")
                    el-checkbox-group(v-model="redEnvelopeRuleForm.selectStreetList")
                      el-checkbox(v-for="( item, index ) in scope.row.streetList", :label="item.streetCode", :key="index", v-on:change="handleCheckedStreetChange(item)") {{item.street}}
          el-form-item.receive(label="红包领取条件", prop="receive")
            el-tooltip(effect="dark", placement="top")
              div(slot="content")
                | 扫码领红包：表示商品到销售终端
                br
                | 开单成功领红包：表示销售成功
                br
                | 开单并且发送短信给消费者领红包：表示销售开单的真实性
                br
                | 扫码收款领红包：表示销售成功的客户支付方式
              i.el-icon-question
            el-select(v-model="redEnvelopeRuleForm.receive", placeholder="请选择红包领取条件")
              el-option(label="扫码领红包", value="0")
              el-option(label="开单成功领红包", value="1")
              el-option(label="开单并且发送短信给消费者领红包", value="2")
              el-option(label="扫码收款开单领红包", value="3")
          el-form-item.activity-time(label="活动时间")
            el-col(:span="4")
              el-form-item(prop="date1")
                el-date-picker(v-model="redEnvelopeRuleForm.date1", value-format="yyyy-MM-dd HH:mm:ss", type="datetime", placeholder="开始时间", style="width:250px")
            el-col.line(:span="1", style="text-align:center;") 至
            el-col(:span="4")
              el-form-item(prop="date2")
                el-date-picker(v-model="redEnvelopeRuleForm.date2", value-format="yyyy-MM-dd HH:mm:ss", type="datetime", placeholder="结束时间", style="width:250px")
          hr
          el-form-item.receive-settings-limit(label="领取设置")
            el-col(:span="8", style="text-align:center;")
              el-switch(v-model="redEnvelopeRuleForm.limit")
          template(v-if="redEnvelopeRuleForm.limit")
            el-alert.receive-tips(title="线下推广场景可使用此功能来支持多个用户扫同一二维码领取红包；选中100%中奖时，相应的，红包总个数将乘以输入框内填写的数字", type="info", :closable="false")
            .receive-settings-other
              span 单个二维码可被最多
              el-form-item(prop="number4")
                el-input(v-model="redEnvelopeRuleForm.number4", placeholder="", style="width:110px")
              span 个不同用户领取红包
            .receive-settings-other
              span 活动能被同一用户领取
              el-form-item(prop="number5")
                el-input(v-model="redEnvelopeRuleForm.number5", placeholder="", style="width:110px")
              span 次数限制
            hr
          el-form-item.receive-ads(label="红包广告位图片", prop="receiveADSImg")
            el-upload.receive-ads-uploader(action="", :show-file-list="false", :before-upload="beforeAvatarUpload", :on-success="handleSuccess")
              img.receive-ads-img(v-if="redEnvelopeRuleForm.receiveADSImg", :src="redEnvelopeRuleForm.receiveADSImg")
              i.el-icon-plus.receive-ads-uploader-icon(v-else="")
            .tips 要求宽480像素、高160像素，大小不超过200kB
          el-form-item.submit-project
            el-button.submit(v-on:click="submitForm('redEnvelopeRuleForm')") 保存
            el-button.preview 预览
            el-button.cancel 取消
</template>

<script>
  import {mapState} from 'vuex'
  import {extend} from '~/plugins/funtions'

  export default {
    data() {
      return {
        redEnvelopeRuleForm: {
          name: '',
          range: '0',
          code1: '',
          code2: '',
          type: '0',
          number1: '',
          number2: '',
          number3: '',
          number4: '',
          number5: '',
          region: '0',
          receive: '',
          date1: '',
          date2: '',
          limit: false,
          userNum: '',
          qrcode: '0',
          mechanism: '0',
          isCertification: false,
          companyName: '',
          selectProvinceList: [],
          selectCityList: [],
          selectCountyList: [],
          selectStreetList: [],
          receiveADSImg: '',
          selectCity: '',
          areaValue: [], // 选中的指定分发区域详情
          areaLevel: {}, // 选中的指定分发区域精确等级
        },
        isShowCounty: false,
        receiveADSImgFile: '',
        redEnvelopeRules: {
          name: [
            {required: true, message: '请输入红包名称', trigger: 'blur'}
          ],
          code1: [
            {required: true, message: '请输入产品追溯码', trigger: 'blur'}
          ],
          code2: [
            {required: true, message: '请输入产品登记证号', trigger: 'blur'}
          ],
          number1: [
            {required: true, message: '请输入单个红包金额', trigger: 'blur'}
          ],
          number2: [
            {required: true, message: '请输入红包总个数', trigger: 'blur'}
          ],
          number3: [
            {required: true, message: '请输入红包总金额', trigger: 'blur'}
          ],
          receive: [
            {required: true, message: '请选择红包领取条件', trigger: 'blur'}
          ],
          date1: [
            {required: true, message: '请选择活动开始时间', trigger: 'blur'}
          ],
          date2: [
            {required: true, message: '请选择活动结束时间', trigger: 'blur'}
          ],
          number4: [
            {required: true, message: '请填写单个二维码可领红包次数', trigger: 'blur'}
          ],
          number5: [
            {required: true, message: '请填写活动能被同一用户领取次数限制', trigger: 'blur'}
          ],
          receiveADSImg: [
            {required: true, message: '请上传活动广告图片', trigger: 'blur'}
          ]
        },
      };
    },
    computed: mapState([
      'provinceList',
      'countyList',
    ]),
    watch: {},
    beforeMount() {
      const self = this
      self.$axios.get('/area/getProvince').then(response => {
        if (response.status >= 200 && response.status < 300) {
          self.$store.commit('setProvinceList', response.data.provinceList)
        }
      })
    },
    mounted: function () {
      this.$nextTick(() => {
        document.querySelector('.el-main').style.background = '#fff';
      });
    },
    methods: {
      handleSuccess(res, file) {
        this.redEnvelopeRuleForm.receiveADSImg = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isPic = file.type === 'image/jpeg' || file.type === 'image/png'
        const isLt200KB = file.size / 1024 / 1024 < 0.2

        this.receiveADSImgFile = file

        if (!isPic) {
          this.$message.error('上传图片只能是 JPG，PNG 格式!');
        }
        if (!isLt200KB) {
          this.$message.error('上传头像图片大小不能超过 200kb!');
        }
        return isPic && isLt200KB;
      },
      goToCertification() {
        const self = this
        self.$router.push('/authenticate')
      },
      /**
       * 省份 - Change
       * @param value
       */
      handleCheckedProvincesChange(value) {
        const self = this
        const isChecked = event.srcElement.checked
        if (!isChecked) {
          // 删除 vuex provinceList 中的 cityList 信息
          const selectCities = self.$store.state.provinceList
          selectCities.map((item, index) => {
            if (item.provinceCode === value.provinceCode) {
              delete item.cityList
            }
          })
        } else {
          self.$axios.get(`/area/getCity/${value.provinceCode}`).then(response => {
            if (response.status >= 200 && response.status < 300) {
              self.$set(value, 'cityList', response.data.cityList)
            }
          })
        }
      },
      /**
       * 市区
       * @param value
       */
      handleCheckedCitiesChange(value) {
        const self = this
        const isChecked = event.srcElement.checked
        if (!isChecked) {
          // 删除 vuex countyList 展示信息 并且隐藏
          self.$store.commit('setCountyList', [])
          self.$delete(value, 'countyList')
          self.isShowCounty = false
        } else {
          this.redEnvelopeRuleForm.selectCity = value.city
          self.$axios.get(`/area/getCounty/${value.cityCode}`).then(response => {
            if (response.status >= 200 && response.status < 300) {
              self.$store.commit('setCountyList', response.data.countyList)
              self.$set(value, 'countyList', response.data.countyList)
              self.isShowCounty = true
            }
          })
        }
      },
      /**
       * 市区 - Click 点击市区编辑按钮的时候加载数据
       * @param value
       * @param dataCities
       */
      handleCheckedCitiesChangeClick(value, dataCities) {
        const self = this
        this.redEnvelopeRuleForm.selectCity = value.city
        dataCities.map((item, index)=>{
          if( item.cityCode === value.cityCode ) {
            self.$store.commit('setCountyList', item.countyList)
          }
        })
      },
      /**
       * 区县
       * @param value
       */
      handleCheckedCountiesChange(value) {
        const self = this
        const isChecked = event.srcElement.checked
        if (!isChecked) {
          // 删除 vuex countyList 中的 streetList 信息
          const selectStreets = self.$store.state.countyList
          selectStreets.map((item, index) => {
            if (item.streetCode === value.streetCode) {
              delete item.streetList
            }
          })
        } else {
          self.$axios.get(`/area/getStreet/${value.countyCode}`).then(response => {
            if (response.status >= 200 && response.status < 300) {
              self.$set(value, 'streetList', response.data.streetList)
            }
          })
        }
      },
      /**
       * 乡镇/街道
       * @param value
       */
      handleCheckedStreetChange(value) {
        const isChecked = event.srcElement.checked

        console.log(value)
      },
      /**
       * 提交表单
       * @param formName
       */
      submitForm(formName) {
        // formData对象
        let formData = new FormData()

        const self = this
        self.$refs[formName].validate((valid) => {
          if (valid) {
            // 提交表单数据
            //======================>
            formData.append('activityName', this.redEnvelopeRuleForm.name) // 活动名称
            formData.append('companyId', 1) // 活动所属企业
            formData.append('totalNum', Number(self.redEnvelopeRuleForm.number2)) // 活动红包总个数
            formData.append('totalAmounts', Number(self.redEnvelopeRuleForm.number3)) // 活动红包总金额
            formData.append('startDate', self.redEnvelopeRuleForm.date1) // 活动开始时间
            formData.append('endDate', self.redEnvelopeRuleForm.date2) // 活动结束时间
            formData.append('bannerImage', this.receiveADSImgFile) // 活动广告图片
            /**
             * 领取条件
             * 0 - 扫码领红包
             * 1 - 开单成功领红包
             * 2 - 开单并发送短信给消费者领红包
             * 3 - 扫码收款开单领红包
             */
            switch (self.redEnvelopeRuleForm.receive) {
              case '0':
                formData.append('receiveConditions', Number(self.redEnvelopeRuleForm.receive))
                break;
              case '1':
                formData.append('receiveConditions', Number(self.redEnvelopeRuleForm.receive))
                break;
              case '2':
                formData.append('receiveConditions', Number(self.redEnvelopeRuleForm.receive))
                break;
              case '3':
                formData.append('receiveConditions', Number(self.redEnvelopeRuleForm.receive))
                break;
            }
            /**
             * 红包范围
             * 0 - 指定产品
             * 1 - 指定二维码
             * 2 - 某类产品
             * 3 - 企业所有产品
             */
            switch (self.redEnvelopeRuleForm.range) {
              case '0':
                formData.append('rangeFlag', Number(self.redEnvelopeRuleForm.range))
                formData.append('rangeValue', self.redEnvelopeRuleForm.code1)
                break;
              case '':
                formData.append('rangeFlag', Number(self.redEnvelopeRuleForm.range))
                break;
              case '2':
                formData.append('rangeFlag', Number(self.redEnvelopeRuleForm.range))
                formData.append('rangeValue', self.redEnvelopeRuleForm.code2)
                break;
              case '3':
                formData.append('rangeFlag', Number(self.redEnvelopeRuleForm.range))
                break;
            }
            /**
             * 红包类型
             * 0 - 随机金额
             * 1 - 固定金额
             */
            switch (self.redEnvelopeRuleForm.type) {
              case '0':
                formData.append('type', Number(self.redEnvelopeRuleForm.type))
                break;
              case '1':
                formData.append('type', Number(self.redEnvelopeRuleForm.type))
                break;
            }
            /**
             * 红包发放区域
             * 0 - 无产品区域
             * 1 - 指定区域
             * 2 - 指定农资店
             */
            switch (self.redEnvelopeRuleForm.region) {
              case '0':
                formData.append('areaFlag', Number(self.redEnvelopeRuleForm.region))
                break;
              case '1':
                formData.append('areaFlag', Number(self.redEnvelopeRuleForm.region))
                formData.append('areaValue', '')
                formData.append('areaLevel', '')
                break;
              case '2':
                formData.append('areaFlag', Number(self.redEnvelopeRuleForm.region))
                break;
            }
            /**
             * 领取设置
             * true
             * false
             */
            if (self.redEnvelopeRuleForm.limit) {
              formData.append('receiveFlag', Boolean(self.redEnvelopeRuleForm.limit))
              formData.append('qrCodeMaxTimes', Number(self.redEnvelopeRuleForm.number4))
              formData.append('canReceiveTimes', Number(self.redEnvelopeRuleForm.number5))
            } else {
              formData.append('receiveFlag', Boolean(self.redEnvelopeRuleForm.limit))
            }

            /**
             * 上传表单信息
             */
            self.$axios.post('/activity/createActivity', formData).then(response => {
              if (response.status >= 200 && response.status < 300) {
                if (response.data.message === '') {
                  self.$notify.success({
                    title: '操作成功！',
                    message: '即将跳转到列表页'
                  })
                  setTimeout(() => {
                    self.$router.push('/redEnvelopeList')
                  }, 1000)
                }
              }
            })
          } else {
            self.$notify.error({
              title: '保存失败！',
              message: '请检查表单是否填写完整！'
            })
            return false
          }
        });
      },
    }
  }
</script>

<style lang="scss">
  .red-envelope-rule-form {
    hr {
      border: 1px #eee solid;
    }

    .range {
      position: relative;

      .el-icon-question {
        position: absolute;
        left: -85px;
        top: 13px;
        cursor: pointer;
      }
    }

    a.certification-false {
      color: #2a98e5;
      font-weight: 600;
      text-decoration: #2a98e5 underline;
      cursor: pointer;

      &:hover {
        color: #2a98e5;
        text-decoration: #2a98e5 underline;
        cursor: pointer;
      }
    }

    .total-number {
    }

    .total-amount {
      .tips {
        display: inline-grid;
        position: relative;
        bottom: 10px;
        left: 40px;

        a {
          line-height: 1.5;
          text-align: center;

          &:first-child {
            font-size: 14px;
          }

          &:last-child {
            font-size: 11px;
          }
        }
      }
    }

    .receive {
      position: relative;

      .el-icon-question {
        position: absolute;
        left: -125px;
        top: 13px;
        cursor: pointer;
      }
    }

    .receive-settings-limit-template {
      margin-bottom: 5px;

      .el-form-item__content {
        display: flex;

        .el-input {
          margin-right: 20px;
        }
      }
    }

    .receive-tips {
      margin-left: 25px;
      width: 830px;
    }

    .receive-settings-other {
      display: flex;
      margin-left: 25px;
      margin-top: 22px;

      .el-form-item {
        .el-form-item__content {
          margin-left: 10px !important;
          margin-right: 10px;
        }
      }

      span {
        color: #606266;
        font-size: 14px;
        height: 40px;
        line-height: 40px;
      }
    }

    .receive-ads {
      .el-form-item__label {
        margin-right: 20px;
        height: 80px;
        line-height: 80px;
        padding-right: 0;
      }

      .receive-ads-uploader {
        .el-upload {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;

          &:hover {
            border-color: $main-style-red;
          }
        }

        .receive-ads-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          width: 240px;
          height: 80px;
          line-height: 80px;
          text-align: center;
        }

        .receive-ads-img {
          width: 240px;
          height: 80px;
          display: block;
        }
      }

      .el-form-item__content {
        display: flex;

        .tips {
          font-size: 14px;
          margin-left: 20px;
          height: 80px;
          line-height: 80px;
        }
      }
    }

    .submit-project {
      .el-button {
        width: 100px;
        color: #fff;
      }

      .submit {
        background-color: $main-style-red;
      }

      .preview {
        background-color: #999;
      }

      .cancel {
        color: initial;
      }
    }

    .el-table {
      margin-left: 180px;
      width: 80%;
      margin-bottom: 20px;
      border-bottom: 1px solid #ebeef5;

      td, th {
        border: 1px solid #ebeef5;
      }

      i.el-icon-edit {
        margin-left: 5px;
        margin-right: 10px;
        font-size: 16px;
        cursor: pointer;
      }
    }
  }
</style>
